package com.talent.study.disruptor.example;

import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.YieldingWaitStrategy;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;

import java.util.concurrent.*;

/**
 * @Author: hszhou
 * @Date: 2025/4/15 9:45
 * @Description: 必须描述类做什么事情, 实现什么功能
 */
public class DisruptorMain {

    public static void main(String[] args) {

        OrderEventFactory eventFactory = new OrderEventFactory();
        // 3.创建ringBuffer 大小
     //   int ringBufferSize = 1024 * 1024; // ringBufferSize大小一定要是2的N次方

        int ringBufferSize = 16;

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                60L, TimeUnit.SECONDS,
                new SynchronousQueue<Runnable>());
        // 1.创建一个可缓存的线程 提供线程来出发Consumer 的事件处理
        ExecutorService executor = Executors.newCachedThreadPool();

        Disruptor<OrderEvent> disruptor = new Disruptor<>(eventFactory,
                ringBufferSize, threadPoolExecutor,
                ProducerType.MULTI, new YieldingWaitStrategy());

        // 5.连接消费端方法
        disruptor.handleEventsWith(new OrderEventHandler());
        // 6.启动
        disruptor.start();
        // 7.创建RingBuffer容器
        RingBuffer<OrderEvent> ringBuffer = disruptor.getRingBuffer();
        // 8.创建生产者
        OrderEventProducer producer = new OrderEventProducer(ringBuffer);

        for (int i = 1; i <= 100; i++) {
            producer.sendData(i+"");
        }
        //10.关闭disruptor和executor
        disruptor.shutdown();
        executor.shutdown();

    }
}
